package com.ym.excel.mq.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ym.excel.model.ExcelModel;
import com.ym.excel.mq.name.MqState;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ExportService {

    ExecutorService service = Executors.newFixedThreadPool(10);

    @RabbitListener(queues = MqState.service_form_export)
    public void export(Map<String, Object> map) {
        //引入线程池，控制并发数
        service.execute(() -> deal(map));
    }

    private void deal(Map<String, Object> map){
        //此处生成临时文件。
        String fileName = this.getClass().getResource("/").getPath() + System.currentTimeMillis() + ".xlsx";
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(fileName).build();
            List<List<ExcelModel>> lists = (List<List<ExcelModel>>) map.get("lists");
            for (int i = 0; i < lists.size(); i++) {
                List<ExcelModel> models = lists.get(i);
                WriteSheet writeSheet = EasyExcel.writerSheet(i, i + 1 + "").head(ExcelModel.class).build();
                excelWriter.write(models, writeSheet);
            }
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
}
